package Mysql_;

import Util.DBUtil;

import java.sql.*;
import java.util.Scanner;

/**
 * @Author 汤舒青
 * @Version 1.0
 */

// insert操作支持返回主键，写个例子。
@SuppressWarnings("all")
public class Mysql02 {
    public static void main(String[] args) {
        Connection con=null;
        PreparedStatement re=null;
        ResultSet res =null;
        Scanner input = new Scanner(System.in);
        try {
           con = DBUtil.getConnection();
            String sql = "INSERT INTO s_subject(subjectname,classhour,gradeid) VALUES (?,?,?)";
           re = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            System.out.println("输入课程名称");
            String sname = input.next();
            System.out.println("输入课时");
            int hour = input.nextInt();
            System.out.println("输入年级号");
            int gid = input.nextInt();
            re.setString(1, sname);
            re.setInt(2, hour);
            re.setInt(3, gid);
            int i1 = re.executeUpdate();
            if (i1 > 0) {
                System.out.println("插入成功");
            } else {
                System.out.println("插入失败");
            }
           res = re.getGeneratedKeys();
            if(res.next()){
                System.out.println("主键为"+res.getObject(1));
            }
            ResultSetMetaData rs = res.getMetaData();

            for (int i = 0; i <rs.getColumnCount() ; i++) {
                System.out.println(rs.getColumnClassName(i+1));
            }


        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(res);
            DBUtil.close(re);
            DBUtil.close(con);


        }


    }
}
